package net.lookyou.boot.demo.config.security.service;

import net.lookyou.boot.demo.entity.SysUser;
import net.lookyou.boot.demo.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 *  <p> 自定义userDetailsService - 认证用户详情 </p>
 *
 * @description :
 * @author : zhengqing
 * @date : 2019/10/14 10:33
 */
@Service
public class PhoneUserDetailsService extends BaseUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    /***
     * 根据账号获取用户信息
     * @param phone:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        SysUser user = userMapper.selectOne(new SysUser(){{
            setPhone(phone);
        }});

        if(!Objects.nonNull(user) || StringUtils.isBlank(user.getPassword())){
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 返回UserDetails实现类
        return new User(user.getUsername(), user.getPassword(),  super.authorities(user));
    }

}
